import React, { Component } from 'react';
import {
  BackHandler,
  StatusBar,
} from 'react-native';

import {
  addNavigationHelpers,
  NavigationActions,
} from 'react-navigation';
import { connect } from 'dva';
import AppNavigator from './RouterConfig';


// 获取到当前屏幕所在的路由
function getCurrentScreen(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  if (route.routes) {
    // [
    //   {
    //   key: 'Init',
    //   routeName: 'Home',
    //   }
    // ]
    return getCurrentScreen(route);
  }
  return route.routeName;
}

@connect(({ router }) => ({ router }))
class Router extends Component {

  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', this.backHandle);
  }

  componentDidMount() {
    StatusBar.setTranslucent(true);
    StatusBar.setBackgroundColor('rgba(0,0,0,.3)');
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandle);
  }

  backHandle = () => {
    const currentScreen = getCurrentScreen(this.props.router);
    if (currentScreen !== 'Home') {
      this.props.dispatch(NavigationActions.back());
      return true;
    }
    return false;
  };

  render() {
    const {
      dispatch,
      router,
    } = this.props;

    // console.log(this.props, 'props');
    // console.log(router, 'routerrouter');

    const navigation = addNavigationHelpers({ dispatch, state: router });
    return <AppNavigator navigation={navigation} />;
  }

}

export function routerReducer(state, action = {}) {
  return AppNavigator.router.getStateForAction(action, state);
}

export default Router;
